package com.wetech.demo.web3j.controller;

import com.wetech.demo.web3j.service.LJY_ERC20Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
@RestController
@RequestMapping("/api/erc20")
@RequiredArgsConstructor
public class LJY_ERC20Controller {

    private final LJY_ERC20Service erc20Service;

    // 部署合约
    @PostMapping("/deploy")
    public CompletableFuture<ResponseEntity<Map<String, String>>> deployContract() {
        return erc20Service.deployContract()
                .thenApply(address -> {
                    Map<String, String> response = new HashMap<>();
                    response.put("contractAddress", address);
                    response.put("message", "LJY_ERC20 contract deployed successfully");
                    return ResponseEntity.ok(response);
                });
    }

    // 加载现有合约
    @PostMapping("/load")
    public ResponseEntity<Map<String, String>> loadContract(@RequestParam String address) {
        erc20Service.loadContract(address);
        Map<String, String> response = new HashMap<>();
        response.put("message", "Contract loaded successfully");
        response.put("contractAddress", address);
        return ResponseEntity.ok(response);
    }

    // 获取代币信息
    @GetMapping("/info")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getTokenInfo() {
        return erc20Service.name()
                .thenCompose(name -> erc20Service.symbol()
                        .thenCompose(symbol -> erc20Service.decimals()
                                .thenCompose(decimals -> erc20Service.totalSupply()
                                        .thenApply(totalSupply -> {
                                            Map<String, Object> response = new HashMap<>();
                                            response.put("name", name);
                                            response.put("symbol", symbol);
                                            response.put("decimals", decimals.toString());
                                            response.put("totalSupply", totalSupply.toString());
                                            response.put("contractAddress", erc20Service.getContractAddress());
                                            return ResponseEntity.ok(response);
                                        }))));
    }

    // 查询余额
    @GetMapping("/balance")
    public CompletableFuture<ResponseEntity<Map<String, String>>> getBalance(@RequestParam String address) {
        return erc20Service.balanceOf(address)
                .thenApply(balance -> {
                    Map<String, String> response = new HashMap<>();
                    response.put("address", address);
                    response.put("balance", balance.toString());
                    response.put("contractAddress", erc20Service.getContractAddress());
                    return ResponseEntity.ok(response);
                });
    }

    // 转账
    @PostMapping("/transfer")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> transfer(
            @RequestParam String to,
            @RequestParam String value) {
        BigInteger amount = new BigInteger(value);
        return erc20Service.transfer(to, amount)
                .thenApply(receipt -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("transactionHash", receipt.getTransactionHash());
                    response.put("blockNumber", receipt.getBlockNumber().toString());
                    response.put("gasUsed", receipt.getGasUsed().toString());
                    response.put("status", receipt.getStatus());
                    response.put("contractAddress", erc20Service.getContractAddress());
                    response.put("message", "Transfer completed successfully");
                    return ResponseEntity.ok(response);
                });
    }

    // 授权
    @PostMapping("/approve")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> approve(
            @RequestParam String spender,
            @RequestParam String value) {
        BigInteger amount = new BigInteger(value);
        return erc20Service.approve(spender, amount)
                .thenApply(receipt -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("transactionHash", receipt.getTransactionHash());
                    response.put("blockNumber", receipt.getBlockNumber().toString());
                    response.put("gasUsed", receipt.getGasUsed().toString());
                    response.put("status", receipt.getStatus());
                    response.put("contractAddress", erc20Service.getContractAddress());
                    response.put("message", "Approval completed successfully");
                    return ResponseEntity.ok(response);
                });
    }

    // 查询授权额度
    @GetMapping("/allowance")
    public CompletableFuture<ResponseEntity<Map<String, String>>> getAllowance(
            @RequestParam String owner,
            @RequestParam String spender) {
        return erc20Service.allowance(owner, spender)
                .thenApply(allowance -> {
                    Map<String, String> response = new HashMap<>();
                    response.put("owner", owner);
                    response.put("spender", spender);
                    response.put("allowance", allowance.toString());
                    response.put("contractAddress", erc20Service.getContractAddress());
                    return ResponseEntity.ok(response);
                });
    }

    // 修改现有的transferFrom方法，添加contractAddress参数
    @PostMapping("/transferFrom")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> transferFrom(
            @RequestParam String contractAddress,  // 新增：代币合约地址
            @RequestParam String from,
            @RequestParam String to,
            @RequestParam String value) {

        BigInteger amount = new BigInteger(value);
        return erc20Service.transferFromWithContract(contractAddress, from, to, amount)
                .thenApply(receipt -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("transactionHash", receipt.getTransactionHash());
                    response.put("blockNumber", receipt.getBlockNumber().toString());
                    response.put("gasUsed", receipt.getGasUsed().toString());
                    response.put("status", receipt.getStatus());
                    response.put("contractAddress", contractAddress);
                    response.put("message", "TransferFrom completed successfully");
                    return ResponseEntity.ok(response);
                });
    }

    // 铸造代币
    @PostMapping("/mint")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> mint(
            @RequestParam String to,
            @RequestParam String value) {
        BigInteger amount = new BigInteger(value);
        return erc20Service.mint(to, amount)
                .thenApply(receipt -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("transactionHash", receipt.getTransactionHash());
                    response.put("blockNumber", receipt.getBlockNumber().toString());
                    response.put("gasUsed", receipt.getGasUsed().toString());
                    response.put("status", receipt.getStatus());
                    response.put("contractAddress", erc20Service.getContractAddress());
                    response.put("message", "Mint completed successfully");
                    return ResponseEntity.ok(response);
                });
    }

    // 销毁代币
    @PostMapping("/burn")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> burn(@RequestParam String value) {
        BigInteger amount = new BigInteger(value);
        return erc20Service.burn(amount)
                .thenApply(receipt -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("transactionHash", receipt.getTransactionHash());
                    response.put("blockNumber", receipt.getBlockNumber().toString());
                    response.put("gasUsed", receipt.getGasUsed().toString());
                    response.put("status", receipt.getStatus());
                    response.put("contractAddress", erc20Service.getContractAddress());
                    response.put("message", "Burn completed successfully");
                    return ResponseEntity.ok(response);
                });
    }

    // 获取合约地址
    @GetMapping("/address")
    public ResponseEntity<Map<String, String>> getContractAddress() {
        String address = erc20Service.getContractAddress();
        Map<String, String> response = new HashMap<>();
        if (address != null) {
            response.put("contractAddress", address);
            return ResponseEntity.ok(response);
        } else {
            response.put("message", "No contract loaded");
            return ResponseEntity.ok(response);
        }
    }
}